import { defineStore } from 'pinia'
import { IMessageStoreType, IMessageType } from '@/store/modules/interface/message'
import { IMessageList } from '@/api/message/type'
import {
	reqGetFriendChatRecordsList,
	reqGetGroupChatRecordsList,
	reqGetMessageList,
	reqMessageRead
} from '@/api/message'
import { reqGetGroupList } from '@/api/contact/index'
import { useUserInfoStore } from '@/store/modules/user'
import router from '@/router'
import utils from '@/utils'
import { baseRes } from '@/api/type'
import socket from '@/socket'

const route = router.currentRoute

// 用户store
const userInfoStore = useUserInfoStore()
export const useMessageStore = defineStore('messageStore', {
	state: (): IMessageStoreType => {
		return {
			messageChatList: [], //消息详情列表
			messageTotal: 0,
			canLoadingMore: false, //是否能刷新更多
			messageList: [], //左侧消息列表
			stagingInfo: {} as IMessageList
		}
	},
	actions: {
		// 获取聊天列表数据
		async getMessageList() {
			const res = await reqGetMessageList(userInfoStore.userInfo._id)
			if (res && res.code === 200) {
				res.data.forEach((i) => {
					Object.assign(i, { userStatus: true })
				})
				this.messageList = res.data
				// 消息总数
				let count = 0
				res.data.forEach((item) => {
					item.unreadMsgCount ? (count += item.unreadMsgCount) : count
				})
				this.messageTotal = count
			}
		},
		// 获取当前好友聊天记录
		async getFriendChatRecordsList(userId: string, friendId: string, pageNum: number) {
			try {
				if (pageNum === 1) {
					this.messageChatList = []
					this.canLoadingMore = true
				}
				const res: baseRes = await reqGetFriendChatRecordsList(userId, friendId, pageNum)

				if (res.code == 200) {
					if (res.data.messageList!.length < 20) {
						// 可以加载更多
						this.canLoadingMore = false
					}
					res.data.messageList?.forEach((item) => {
						item.time = utils.formatTime(new Date(item.time))
						item.messageStatus = true
					})
					this.messageChatList.unshift(...res.data.messageList)
					console.log('聊天记录', this.messageChatList)
				} else if (res.code === 202) {
					utils.msg('不是您的好友!', 'error')
				} else if (res.code === 201) {
					// 咱无更多
					this.canLoadingMore = false
				}
			} catch (e) {}
		},
		// 把消息Push到聊天详情列表里面
		pushMessageData(data: IMessageType) {
			console.log('eeee', data)
			const type = route.value.query.type
			const friendId = route.value.query.id
			console.log('pushData', data)
			try {
				// 是否删除
				const userStatus = this.messageList.filter((item) => item._id === friendId)[0].userStatus
				Object.assign(data, {
					messageStatus: userStatus
				})
				this.messageChatList.push(data)
			} catch (e) {
				console.log(e)
				const msg = type === 'friend' ? '你与ta还不是好友' : '你不在群聊中'
				utils.msg(msg, 'error')
			}
		},
		//保存主页的信息
		saveStagingInfo(info) {
			this.stagingInfo = info
		},
		// 连接所有的群聊
		async getAllGroup() {
			const res: baseRes = await reqGetGroupList(userInfoStore.userInfo._id)
			if (res.code == 200) {
				res.data.forEach((item) => {
					// 把用户加入所有已经加过的群聊
					socket.emit('join_group', item.groupId._id)
				})
			}
		},
		// 消息设置为已读
		async setMessageRead() {
			const currentIndex = this.messageList.findIndex((item) => item._id === route.value.query.id)
			if (currentIndex == -1 || !this.messageList[currentIndex].unreadMsgCount) return

			// 修改store的消息数
			// 该好友发来的消息未读总数
			const thisUnread = this.messageList[currentIndex].unreadMsgCount
			// 左侧消息总数
			this.messageTotal = this.messageTotal - thisUnread
			// 修改与该好友的未读消息数
			this.messageList[currentIndex].unreadMsgCount = 0
			await this.triggerMessageRead()
		},
		// 触发请求
		async triggerMessageRead() {
			const type = route.value.query.type as string
			const userId = userInfoStore.userInfo._id
			const id = route.value.query.id as string
			await reqMessageRead(type, userId, id)
		},
		// 获取当前群聊天记录消息
		async getGroupChatRecordsList(userId: string, groupId: string, pageNum: number) {
			try {
				if (pageNum == 1) {
					this.messageChatList = []
					this.canLoadingMore = true
				}
				const res: baseRes = await reqGetGroupChatRecordsList(userId, groupId, pageNum)
				if (res && res.code === 200 && res.data.messageList?.length > 0) {
					if (res.data.messageList!.length < 20) {
						// 可以加载更多
						this.canLoadingMore = false
					}
					res.data.messageList?.forEach((item) => {
						item.time = utils.formatTime(new Date(item.time))
						item.messageStatus = true
					})
					this.messageChatList.unshift(...res.data.messageList)
				} else if (res.code === 202) {
					// utils.msg(res.msg, 'error')
				} else if (res.code === 201) {
					this.canLoadingMore = false
				}
			} catch (e) {
				utils.msg('请求失败', 'error')
			}
		},
		clearStagingInfo() {
			this.stagingInfo = {
				imgUrl: '',
				type: '',
				unreadMsgCount: 0,
				_id: '',
				userStatus: true
			}
		},
		updateMessageData(data: IMessageType, index: number) {
			this.messageChatList[index] = data
		},
		// 删除聊天详情列表数据
		delMessageData(index: number) {
			this.messageChatList.splice(index, 1)
		}
	}
})
